package sword.T35;

/**
 * @Author: duyuzhou
 * @Create: 2022-04-08 1:07:47 星期五
 */
public class Solution {

    class Node {
        int val;
        Node next;
        Node random;

        public Node(int val) {
            this.val = val;
            this.next = null;
            this.random = null;
        }
    }

    public Node copyRandomList(Solution.Node head) {
        Solution.Node p = head;
        while (p != null) {
            Solution.Node temp = new Solution.Node(p.val);
            temp.next = p.next;
            p.next = temp;
            p = temp.next;
        }
        p = head;
        while (p != null) {
            if (p.random != null)
                p.next.random = p.random.next;
            p = p.next.next;
        }
        if (head == null)
            return null;
        p = head;
        Solution.Node tHead = head.next, q = tHead;
        while (p != null) {
            p.next = q.next;
            p = p.next;
            if (p == null) {
                break;
            }
            q.next = p.next;
            q = q.next;
        }
        return tHead;
    }
}
